#!/usr/bin/env python

###
# Wifi + GPS fingerprint collection tool
# Copyright (c) 2008, Yura Zenevich, Jorge Silva, and Jamon Camisso
# Homepage http://wiki.scyp.atrc.utoronto.ca/wiki/WiFiPositioning
# Contact scyp@atrc.utoronto.ca
#    
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program, see enclosed file gpl-3.txt or browse to
# <http://www.gnu.org/licenses/gpl.txt>
###

from Search import *
from Address import *
import sys

#	FIND THE FLOOR ID AND RETURN FILTERED LIST OF ADJACENT SCANS CONTAING ONLY
#	SCANS FROM THE FLOOR THAT WE THINK WE ARE ON.
def FloorFind(scan, scans):

	floors = []
	uniqueFloorIds = []
	finalScans = []
	minFloorLS = sys.maxint
	resultFloorId = -1

	for s in scans:
		if uniqueFloorIds.count(s[3]) == 0:
			uniqueFloorIds.append(s[3])
		#endif
	#endfor
		
	for fid in uniqueFloorIds:
		floorVector = []
		for macAddress in scan[0]:
			floorVector.append((macAddress, Search().FindFloorValue(fid, macAddress)))
		#endfor
		floors.append((fid, floorVector))
	#endfor
	for uf in floors:
		tmpLS = CalculateLS(uf, scan)
		if (tmpLS < minFloorLS):
			minFloorLS = tmpLS
			resultFloorId = uf[0]
		#endif
	#endfor

	for s in scans:
		if s[3] == resultFloorId:
			finalScans.append(s)
		#endif
	#endfor
	floorNumberBuildingName = Addresses().ReturnBuildingNameFromFloorId(resultFloorId)
	return floorNumberBuildingName[0], floorNumberBuildingName[1], finalScans	

#end FloorFind

#	CALCULATE THE LEAST SQUARE SUM FOR THE NEW MAC VECTOR AND AVERAGED
#	ADJACENT FLOOR MAC VECTOR.
def CalculateLS(uf, scan):

	LS = 0

	for macAddress in scan[0]:
		LS = LS + (scan[2][scan[0].index(macAddress)] - uf[1][scan[0].index(macAddress)][1])**2
	#endfor

	return LS
